//
//  ScanCodeViewController.m
//  JiuLe
//
//  Created by 黄鑫 on 16/8/29.
//  Copyright © 2016年 Fine. All rights reserved.
//

#import "ScanCodeViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AVFoundation/AVCaptureOutput.h>
#import "Balloon.h"
#import <GTSDK/GeTuiSdk.h>
#import "HomeViewController.h"
#import "BaseNavController.h"
#import "ActivationViewController.h"
#import "NSString+Date.h"

#define SCANSPACEOFFSET 0.1f
#define REMINDTEXT @"将二维码/条码放入框内，即可自动扫描"
#define SCREENBOUNDS [UIScreen mainScreen].bounds
#define SCREENWIDTH CGRectGetWidth([UIScreen mainScreen].bounds)
#define SCREENHEIGHT CGRectGetHeight([UIScreen mainScreen].bounds)

@interface ScanCodeViewController ()<AVCaptureMetadataOutputObjectsDelegate>//用于处理采集信息的代理
{
    AVCaptureSession * session;//输入输出的中间桥梁
}

@property (nonatomic, strong) AVCaptureMetadataOutput * output;
@property (nonatomic, strong) UILabel * remind;
@property (nonatomic, strong) IBOutlet UIImageView * scanImage;
@property (nonatomic, assign) CGRect scanRect;
@property (nonatomic, strong) CAShapeLayer * maskLayer;
@property (nonatomic, strong) CAShapeLayer * shadowLayer;
@property (nonatomic, strong) CAShapeLayer * scanRectLayer;
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *passWord;

@end

@implementation ScanCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"扫描标签上二维码";
    //获取摄像设备
    AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //创建输入流
    AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    //创建输出流
     _output = [[AVCaptureMetadataOutput alloc]init];
    //设置代理 在主线程里刷新
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    //初始化链接对象
    session = [[AVCaptureSession alloc]init];
    //高质量采集率
    [session setSessionPreset:AVCaptureSessionPresetHigh];
    [session addInput:input];
    [session addOutput:_output];
    //设置扫码支持的编码格式(如下设置条形码和二维码兼容)
    _output.metadataObjectTypes=@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
    AVCaptureVideoPreviewLayer * layer = [AVCaptureVideoPreviewLayer layerWithSession:session];
    layer.videoGravity=AVLayerVideoGravityResizeAspectFill;
    layer.frame=self.view.layer.bounds;
    [self.view.layer insertSublayer:layer atIndex:0];
    
    //设置扫描范围
    _output.rectOfInterest = CGRectMake(.18, SCANSPACEOFFSET, 0.52, (1 - SCANSPACEOFFSET * 2));
    //开始捕获
    [session startRunning];
    [self scanImageStart];
    [self.view addSubview:self.remind];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

#pragma  mark - AVCaptureMetadataOutputObjectsDelegate
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    if (metadataObjects.count>0) {
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex : 0 ];
        //输出扫描字符串
        NSLog(@"%@",metadataObject.stringValue);
        NSArray *arr = [metadataObject.stringValue componentsSeparatedByString:@"/"];
        if (arr.count < 4) {
            [SVProgressHUD showSuccessWithStatus:@"请扫描久乐二维码!"];
            return;
        }
        self.passWord = arr[arr.count-2];
        self.name = arr[arr.count -4];
        [session stopRunning];
        [_scanImage.layer removeAllAnimations];
        [self login];
    }
}


/**
 *  滚动扫描图片
 */
- (void)scanImageStart{
    if (SCREENWIDTH == 320 && SCREENHEIGHT == 480) {
        _scanImage.frame = CGRectMake((SCREENWIDTH-206)/2, 100, 206, 2);
    }else if(SCREENWIDTH == 320 && SCREENHEIGHT == 568){
        _scanImage.frame = CGRectMake((SCREENWIDTH-206)/2, 118, 206, 2);
    }else if(SCREENWIDTH == 375){
        _scanImage.frame = CGRectMake((SCREENWIDTH-238)/2, 138, 238, 2);
    }else if(SCREENWIDTH == 414){
        _scanImage.frame = CGRectMake((SCREENWIDTH-277)/2, 158, 277, 2);
    }
    _scanImage.image = [UIImage imageNamed:@"light"];
    [UIView animateWithDuration:2.5 delay:0.0 options:UIViewAnimationOptionRepeat animations:^{
        if (SCREENWIDTH == 320 && SCREENHEIGHT == 480) {
            _scanImage.frame = CGRectMake((SCREENWIDTH-206)/2, 275, 206, 2);
        }else if(SCREENWIDTH == 320 && SCREENHEIGHT == 568){
            _scanImage.frame = CGRectMake((SCREENWIDTH-206)/2, 325, 206, 2);
        }else if(SCREENWIDTH == 375){
            _scanImage.frame = CGRectMake((SCREENWIDTH-238)/2, 382, 238, 2);
        }else if(SCREENWIDTH == 414){
            _scanImage.frame = CGRectMake((SCREENWIDTH-277)/2, 420, 277, 2);
        }
    } completion:^(BOOL finished){
    }];
}


#pragma  mark set/get
/**
 *  提示文本
 */
- (UILabel *)remind
{
    if (!_remind) {
        _remind = [[UILabel alloc] init];
        if (SCREENWIDTH == 320 && SCREENHEIGHT == 480) {
            _remind.frame = CGRectMake(0, 285, SCREENWIDTH, 25);
        }else if(SCREENWIDTH == 320 && SCREENHEIGHT == 568){
            _remind.frame = CGRectMake(0, 339, SCREENWIDTH, 25);
        }else if(SCREENWIDTH == 375){
            _remind.frame = CGRectMake(0, 397, SCREENWIDTH, 25);
        }else if(SCREENWIDTH == 414){
            _remind.frame = CGRectMake(0, 434, SCREENWIDTH, 25);
        }
        _remind.font = [UIFont systemFontOfSize: 15.f * SCREENWIDTH / 375.f];
        _remind.textColor = [UIColor whiteColor];
        _remind.textAlignment = NSTextAlignmentCenter;
        _remind.text = REMINDTEXT;
        _remind.backgroundColor = [UIColor clearColor];
    }
    return _remind;
}

/**
 *  扫描框
 */
- (CAShapeLayer *)scanRectLayer
{
    if (!_scanRectLayer) {
        CGRect scanRect = self.scanRect;
        scanRect.origin.x -= 1;
        scanRect.origin.y -= 1;
        scanRect.size.width += 2;
        scanRect.size.height += 2;
        
        _scanRectLayer = [CAShapeLayer layer];
        _scanRectLayer.path = [UIBezierPath bezierPathWithRect: scanRect].CGPath;
        _scanRectLayer.fillColor = [UIColor clearColor].CGColor;
        _scanRectLayer.strokeColor = [UIColor orangeColor].CGColor;
    }
    return _scanRectLayer;
}

/**
 *  扫描范围
 */
- (CGRect)scanRect
{
    if (CGRectEqualToRect(_scanRect, CGRectZero)) {
        CGRect rectOfInterest = self.output.rectOfInterest;
        CGFloat yOffset = rectOfInterest.size.width - rectOfInterest.origin.x;
        CGFloat xOffset = 1 - 2 * SCANSPACEOFFSET;
        _scanRect = CGRectMake(rectOfInterest.origin.y * SCREENWIDTH, rectOfInterest.origin.x * SCREENHEIGHT, xOffset * SCREENWIDTH, yOffset * SCREENHEIGHT);
    }
    return _scanRect;
}

/**
 *  阴影层
 */
- (CAShapeLayer *)shadowLayer
{
    if (!_shadowLayer) {
        _shadowLayer = [CAShapeLayer layer];
        _shadowLayer.path = [UIBezierPath bezierPathWithRect: self.view.frame].CGPath;
        _shadowLayer.fillColor = [UIColor colorWithWhite: 0 alpha: 0.75].CGColor;
        _shadowLayer.mask = self.maskLayer;
    }
    return _shadowLayer;
}

/**
 *  遮掩层
 */
- (CAShapeLayer *)maskLayer
{
    if (!_maskLayer) {
        _maskLayer = [CAShapeLayer layer];
        _maskLayer = [self generateMaskLayerWithRect: SCREENBOUNDS exceptRect: self.scanRect];
    }
    return _maskLayer;
}


#pragma mark - generate
/**
 *  生成空缺部分rect的layer
 */
- (CAShapeLayer *)generateMaskLayerWithRect: (CGRect)rect exceptRect: (CGRect)exceptRect
{
    CAShapeLayer * maskLayer = [CAShapeLayer layer];
    if (!CGRectContainsRect(rect, exceptRect)) {
        return nil;
    }
    else if (CGRectEqualToRect(rect, CGRectZero)) {
        maskLayer.path = [UIBezierPath bezierPathWithRect: rect].CGPath;
        return maskLayer;
    }
    
    CGFloat boundsInitX = CGRectGetMinX(rect);
    CGFloat boundsInitY = CGRectGetMinY(rect);
    CGFloat boundsWidth = CGRectGetWidth(rect);
    CGFloat boundsHeight = CGRectGetHeight(rect);
    
    CGFloat minX = CGRectGetMinX(exceptRect);
    CGFloat maxX = CGRectGetMaxX(exceptRect);
    CGFloat minY = CGRectGetMinY(exceptRect);
    CGFloat maxY = CGRectGetMaxY(exceptRect);
    CGFloat width = CGRectGetWidth(exceptRect);
    
    /** 添加路径*/
    UIBezierPath * path = [UIBezierPath bezierPathWithRect: CGRectMake(boundsInitX, boundsInitY, minX, boundsHeight)];
    [path appendPath: [UIBezierPath bezierPathWithRect: CGRectMake(minX, boundsInitY, width, minY)]];
    [path appendPath: [UIBezierPath bezierPathWithRect: CGRectMake(maxX, boundsInitY, boundsWidth - maxX, boundsHeight)]];
    [path appendPath: [UIBezierPath bezierPathWithRect: CGRectMake(minX, maxY, width, boundsHeight - maxY)]];
    maskLayer.path = path.CGPath;
    return maskLayer;
}

- (IBAction)backAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma  mark - 私有方法
- (void)login{
    __weak ScanCodeViewController *weakSelf = self;
    [SVProgressHUD showWithStatus:@"登录中.." maskType:SVProgressHUDMaskTypeClear];
    [[BaseDataRequest alloc] userLoginName:self.name password:self.passWord withBlock:^(id responseObject, NSString *status, NSError *error) {
        [SVProgressHUD dismiss];
        if ([status isEqualToString:@"0"]) {
            NSDictionary *result = [responseObject objectForKey:@"result"];
            NSInteger active = [[result objectForKey:@"is_active"] integerValue];
            [NSUserDefaults setObject:self.name forKey:UserDataName];
            [NSUserDefaults setObject:self.passWord forKey:UserDataPassWord];
            [NSUserDefaults setObject:[result objectForKey:@"serial_number"] forKey:TerminalEquipment];
            [NSUserDefaults setObject:@"normal" forKey:UserLoginType];
            if (active == 1) {//未激活
                Balloon *balloon = [[Balloon alloc] init];
                [balloon showTips:@"检查到您是新用户，即将进入激活页面"];
                [weakSelf performSelector:@selector(toActivation)
                               withObject:@{@"bol":@(YES)}
                               afterDelay:1.5f];
            }else{
                BOOL bol =  [[[NSUserDefaults standardUserDefaults] objectForKey:@"is_active"] boolValue];
                if (bol==NO) {
                    [GeTuiSdk bindAlias:[result objectForKey:@"user_id"]];
                }
                [NSUserDefaults setObject:[result objectForKey:@"gender"]  forKey:UserSex];
                [NSUserDefaults setObject:[result objectForKey:@"height"]  forKey:UserHeight];
                [NSUserDefaults setObject:[result objectForKey:@"weight"]  forKey:UserWeight];
                [NSUserDefaults setObject:[result objectForKey:@"user_id"] forKey:UserDataID];
                [NSUserDefaults setObject:[result objectForKey:@"token"] forKey:UserToken];
                [NSUserDefaults setObject:[result objectForKey:@"serial_number"] forKey:UserCCID];
                [[NSUserDefaults standardUserDefaults]setObject:[result objectForKey:@"ispush"] forKey:UserPush];
                NSString *activetime = [[NSString alloc] timeStamp:[result objectForKey:@"activetime"]];
                [NSUserDefaults setObject:activetime forKey:ActivationDate];
                [SVProgressHUD showSuccessWithStatus:@"登录成功!"];
                [weakSelf performSelector:@selector(setRootController)
                               withObject:@{@"bol":@(YES)}
                               afterDelay:1.f];
            }
        }else{
            if (error != nil) {
                TIPSFORVIEW(@"请检测网络设置");
            }else{
                TIPSFORVIEW([responseObject objectForKey:@"message"]);
                [session startRunning];
                [self scanImageStart];
            }
        }
    }];
}

- (void)backTo{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setRootController {
    HomeViewController *home = [[HomeViewController alloc]initWithNibName:@"HomeViewController" bundle:nil];
    BaseNavController *baseNav = [[BaseNavController alloc] initWithRootViewController:home];
    [UIApplication sharedApplication].delegate.window.rootViewController    = baseNav;
}

- (void)toActivation{
    ActivationViewController *activation = [[UIStoryboard storyboardWithName:@"ActivationViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"ActivationViewController"];
    activation.sequenceCode = self.name;
    activation.from = @"2";
    [self.navigationController pushViewController:activation animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
